<template>
  <div class="search-suggestion">
    <van-cell
      icon="search"
      v-for="(str, index) in suggestions"
      :key="index"
      @click="$emit('search', str)"
    >
      <div slot="title" v-html="highlight(str)"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestions } from "@/api/search";
import { debounce } from "lodash";
export default {
  name: "SearchSuggestion",
  components: {},
  props: {
    searchText: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      suggestions: [], //联想建议列表
    };
  },
  computed: {},
  watch: {
    //属性名：要监听的数据名称
    searchText: {
      handler: debounce(async function () {
        const { data } = await getSearchSuggestions(this.searchText);
        this.suggestions = data.data.options;
      }, 200),
      immediate: true,
      //当数据发生变化则会执行handler处理函数
      //   async handler() {
      //     //找到数据接口
      //     //请求获取数据
      //     //模板绑定展示
      //     const { data } = await getSearchSuggestions(this.searchText);
      //     this.suggestions = data.data.options;
      //   },
    },
  },
  created() {},
  mounted() {},
  methods: {
    highlight(str) {
      return str.replace(
        new RegExp(this.searchText, "gi"),
        `<span style="color:red">${this.searchText}</span>`
      );
    },
  },
};
</script>

<style scoped lang="less"></style>